import 'package:boss/ui/widget/image/default_failed_image.dart';
import 'package:boss/ui/widget/image/default_placeholder_image.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

class BaseImage extends StatelessWidget {
  final String imageURL;
  final double width;
  final double height;
  final BoxFit fit;
  final BorderRadius borderRadius;
  final Color color;
  final Widget placeholder;
  final Widget errorWidget;

  bool get isNetWorkImage {
    var reg = RegExp(r'^(assets/image/)\w+');
    return !reg.hasMatch(imageURL);
  }

  const BaseImage(
    this.imageURL, {
    Key key,
    this.width,
    this.height,
    this.fit = BoxFit.cover,
    this.borderRadius,
    this.color,
    this.placeholder,
    this.errorWidget,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    Widget placeholder = this.placeholder ?? DefaultPlaceHolderImage(width: width, height: height);
    Widget errorWidget = this.errorWidget ?? DefaultFailedImage(width: width, height: height);

    Widget imageWidget;

    if (imageURL == '' || imageURL == null) {
      imageWidget = placeholder;
    } else if (isNetWorkImage) {
      imageWidget = CachedNetworkImage(
        imageUrl: '$imageURL?x-oss-process=image/auto-orient,0',
        width: width,
        height: height,
        fit: fit,
        color: color,
        placeholder: (context, url) => placeholder,
        errorWidget: (context, url, error) => errorWidget,
      );
    } else {
      imageWidget = Image.asset(imageURL, width: width, height: height, fit: fit, color: color);
    }

    if (borderRadius != null) {
      imageWidget = ClipRRect(borderRadius: borderRadius, child: imageWidget);
    }

    return RepaintBoundary(child: imageWidget);
  }
}
